var manageClassesCtrl = myApp.controller('manageClassesCtrl', ['$scope', '$rootScope' ,'NgTableParams', function($scope, $rootScope, NgTableParams) {
	$rootScope.firstType = Tools.permissionList[4].permissionId;
	$rootScope.secondType = Tools.permissionList[4].sonPermission[3].permissionId;
	
	$scope.newClassItem = {};
	$scope.modClassItem = {};
	$scope.delClassItem = {};
	$scope.otherTea = {};

	// 提示弹层
	$scope.msg = "";
	$scope.visible = false;

	// 分页 
	$scope.pageList = [];
	$scope.curPage = 1;
	$scope.totalPage = 1;
	$scope.totalRow = 0;
	var PAGESIZE = 10;



	// 设置年份
	$scope.setYearList = function() {
		var data = {};
		commonSrv.getSchoolYears(data, function(result) {
			if(result.status == 0) {
				var list = result.data;
				$scope.yearList = list;
				if($scope.yearList.length > 0) {
					$scope.curYear = list[0];
					$scope.selectYear($scope.curYear);
				}
			}
		},  function(result) {
			if(result.status == 1) {
				alert(result.msg);
			}
		},  function() {
			$scope.$apply();
		});
	};
	// 选择年份
	$scope.selectYear = function() {
		$scope.getClassesList(1);
	};
	// 获取班级类型列表
	$scope.getClassTypeList = function() {
		var data = {};
		commonSrv.getClassTypeList(data, function(result) {
			if (result.status == 0) {
				$scope.classTypeList = result.data;
			}
		},  function(result) {
			if(result.status == 1) {
				alert(result.msg);
			}
		},  function() {
			$scope.$apply();
		});
	};
	/**
	 * 获取班级列表
	 * @param  {[type]} curPage      [要访问第几页]
	 * @param  {[type]} schoolYearId [学年id]
	 */
	$scope.getClassesList = function(curPage) {
		var data ={
			curPage: curPage,
			pagesize: PAGESIZE,
			schoolYearId: $scope.curYear.year
		};
		commonSrv.getClassesList(data, function(result) {
			if(result.status == 0) {
				var list = result.data;
				$scope.classList = new NgTableParams({count: PAGESIZE}, { counts: [],  dataset: list});
				var paginate = result.paginate;
				$scope.totalPage = paginate.totalPage;
				$scope.totalRow = paginate.totalRow;
				$scope.setPage(curPage);
			}
		}, function(result) {
			if(result.status == 1) {
				alert(result.msg);
			}
		}, function() {
			$scope.$apply();
		});
	};

	// 设置分页
	$scope.setPage = function(curPage) {
		var newPageList = [];
		if (curPage < 1 || curPage > $scope.totalPage) {
			alert("设置分页失败");
			return;
		}
		var SHOWSIZE = 5;
		// 总页数小于SHOWSIZE
		if($scope.totalPage <= SHOWSIZE) {
			for(var i=0; i<$scope.totalPage; i++) {
				newPageList.push(i+1);
			}
		// 总页数大于等于SHOWSIZE
		} else {
			if(curPage > 2) {
				// 最后5页
				if(($scope.totalPage - curPage) < 2) {
					for(var i = ($scope.totalPage - 5); i < $scope.totalPage; i++) {
						newPageList.push(i + 1);
					}
				} else {
					for (var i = (curPage - 3); i < ((curPage + 2) > $scope.totalPage ? $scope.totalPage : (curPage + 2)); i++) {
                        newPageList.push(i + 1);
                    }
				}
			} else {
				for(var i=0; i<SHOWSIZE; i++) {
					newPageList.push(i + 1);
				}
			}
		}
        $scope.pageList = newPageList;
        $scope.curPage = curPage;
	};

	//设置当前选中页样式
    $scope.isActivePage = function (page) {
        return $scope.curPage == page;
    };
    //上一页
    $scope.previous = function () {
        if($scope.curPage > 1) {
        	$scope.getClassesList($scope.curPage - 1);
        }
    }
    //下一页
    $scope.next = function () {
        if($scope.curPage < $scope.totalPage) {
        	$scope.getClassesList($scope.curPage + 1);
        }
    };


    // 新增
    // 打开添加班级弹层
	$scope.openAdd = function() {
		var data = {};
		commonSrv.addClassesForm(data, function(result) {
			if(result.status == 0) {
				$scope.newClassItem = result.data;
				$scope.newClassItem.name = "";	
				$scope.newClassItem.description = "";
				$scope.newClassItem.logo = [];
				$scope.newClassItem.maxQuotas = 0;
				$scope.newClassItem.schoolYearId = "";
				$scope.newClassItem.sortNum = 0;
				$scope.newClassItem.select = {
					classTypeId: {},
					calendarId: "",
					userId: {}
				};
				$scope.newClassItem.warn = {
					name: "",
					classTypeId: "",
					maxQuotas: ""
				};
				$('#addClassModel').modal({backdrop: 'static', keyboard: false, show: true});
			}
		},  function(result) {
			if(result.status == 1) {
				alert(result.msg);
			}
		},  function() {
			$scope.$apply();
		});
		
    };   
    // 添加班级
    $scope.addClasses = function() {
    	$scope.watchName('new');
    	$scope.watchClassTypeId('new');
    	$scope.watchMaxQuotas('new');
    	// 判断是否能提交 
    	if($scope.newClassItem.warn.name || $scope.newClassItem.warn.classTypeId || $scope.newClassItem.warn.maxQuotas) {
    		alert("请修改表单");
    		return;
    	}

    	// 名称
    	
    	// 	班级类别id
    	var classTypeId = 0;
    	if($scope.newClassItem.select.classTypeId == null) {
    		classTypeId = 0;
    	} else if(!$scope.newClassItem.select.classTypeId.id) {
    		classTypeId = 0;
    	} else {
    		classTypeId = $scope.newClassItem.select.classTypeId.id;
    	}
    	// 班徽
    	var logo = "";
    	if($scope.newClassItem.logo == null || $scope.newClassItem.logo == undefined) {
    		logo = "";
    	} else {
			logo = $scope.newClassItem.logo;
    	}

    	// 最大学生数
    	var maxQuotas = 0;
    	if($scope.newClassItem.maxQuotas == null || $scope.newClassItem.maxQuotas == undefined) {
    		maxQuotas = 0;
    	} else {
    		maxQuotas = $scope.newClassItem.maxQuotas;
    	}

    	// 考勤日历id
    	var calendarId = 0;
    	if($scope.newClassItem.select.calendarId == null) {
    		calendarId = 0;
    	} else if(!$scope.newClassItem.select.calendarId.calendarId) {
    		calendarId = 0;
    	} else {
    		calendarId = $scope.newClassItem.select.calendarId.calendarId;
    	}

    	// 主教老师
    	var userId = 0;
    	if($scope.newClassItem.select.userId == null) {
    		userId = 0;
    	} else if(!$scope.newClassItem.select.userId.userId) {
    		userId = 0;
    	} else {
    		userId = $scope.newClassItem.select.userId.userId;
    	}
    	// 序号
    	var sortNum = "";
    	if($scope.newClassItem.sortNum == null || $scope.newClassItem.sortNum == undefined) {
    		sortNum = "";
    	} else {
    		sortNum = $scope.newClassItem.sortNum;
    	}

    	// 描述 
    	var description = "";
    	if($scope.newClassItem.description == null || !$scope.newClassItem.description) {
    		description = "";
    	} else {
    		description = $scope.newClassItem.description;
    	}

    	// 判断是否上传了logo
    	if(logo.length > 0) {
    		var formData = new FormData();
			formData.append('file', logo[0]);
			$.ajax({
				url: Tools.config.domain + '/ta/UploadCtrl/uploadPic.do',
				data: formData,
				type: 'POST',
	    		cache: false,
			    processData: false,
			    contentType: false,
				success: function(result) {
					if(typeof result == 'string') {
						result = JSON.parse(result);
					}
					if(result.status == 0) {
						var logoName = result.data;
			    		var postData = {
							calendarId: calendarId,
							classTypeId: classTypeId,
							description: description,
							logo: logoName,	
							maxQuotas: maxQuotas,	
							name: $scope.newClassItem.name,	
							schoolYearId: $scope.curYear.year,
							sortNum: sortNum,	
							userId: userId,
				    	};
				    	commonSrv.addClasses(postData, function(result) {
				    		if(result.status == 0) {
				    			$('#addClassModel').modal('hide');
				    			$scope.msg = "新增成功";
				    			$scope.visible = true;
				    			$scope.getClassesList($scope.curPage);
				    		}
				    	}, function(result) {
				    		if(result.status == 1) {
				    			alert(result.msg);
				    		}
				    	}, function() {
				    		$scope.$apply();
				    	});
					}
				},
				fail: function(result) {
					if(result.status == 3 || result.status == 1) {
						alert(result.msg);
					}
				},
				complete: function() {
					$scope.$apply();
				}
			});
    	} else {
    		var data = {
				calendarId: calendarId,
				classTypeId: classTypeId,
				description: description,
				logo: "",	
				maxQuotas: maxQuotas,	
				name: $scope.newClassItem.name,	
				schoolYearId: $scope.curYear.year,	
				sortNum: sortNum,	
				userId: userId,
	    	};
	    	commonSrv.addClasses(data, function(result) {
				if(result.status == 0) {
					$('#addClassModel').modal('hide');
	    			$scope.msg = "新增成功";
	    			$scope.visible = true;
	    			$scope.getClassesList($scope.curPage);
				}
			},  function(result) {
				if(result.status == 1) {
					alert(result.msg);
				}
			},  function() {
				$scope.$apply();
			});
    	}
    };

    // 新增-上传logo
    $scope.uploadLogo = function(type, file) {
    	if (!file || file.length == 0) {
            return;
        }
        var uploadFiles;
        if (angular.isArray(file)) {
            uploadFiles = file;
        } else {
            uploadFiles = [file];
        }
        if(type == 'new') {
	    	$scope.newClassItem.logo = uploadFiles;
	    } else if(type == 'edit') {
	    	$scope.modClassItem.classes.logo = uploadFiles;
	    }
    };
    // 新增-删除logo
    $scope.delete = function(type) {
    	if(type == 'new') {
	    	$scope.newClassItem.logo = [];
	    } else if(type == 'edit') {
	    	$scope.modClassItem.classes.logo = [];
	    }
    };
    // 新增-下载logo
    $scope.download = function(file) {
    	console.log(file);
    };
    // 打开批量开班弹层
    $scope.openBulk = function() {

    };
    // 批量开班

    // 修改
   	// 打开修改弹层 
    $scope.openEdit = function(item) {
    	var data = {
    		classesId: item.classesId
    	};
    	commonSrv.editOtherClassesForm(data, function(result) {
				if(result.status == 0) {
					$('#editClassModel').modal({backdrop: 'static', keyboard: false, show: true});
					$scope.modClassItem = result.data;
					$scope.modClassItem.otherClassesUser = new NgTableParams({count: PAGESIZE}, { counts: [],  dataset: $scope.modClassItem.otherClassesUser});
					$scope.modClassItem.select = {
						classTypeId: 0,
						calendarId: "",
						userId: 0

					};
					// logo
					if($scope.modClassItem.classes.logo.length > 0) {
						$scope.modClassItem.classes.logo = [$scope.modClassItem.classes.logo];
					} else {
						$scope.modClassItem.classes.logo = [];
					}
					// 班级类别
					for (var i in $scope.modClassItem.classTypeList) {
						if($scope.modClassItem.classes.classTypeId == $scope.modClassItem.classTypeList[i].id) {
							$scope.modClassItem.select.classTypeId = $scope.modClassItem.classTypeList[i];
							break;
						}
					}
					// 考勤日历
					for (var i in $scope.modClassItem.calendarList) {
						if($scope.modClassItem.classes.calendarId == $scope.modClassItem.calendarList[i].calendarId) {
							$scope.modClassItem.select.calendarId = $scope.modClassItem.calendarList[i];
							break;
						}
					}
					// 主教老师
					for (var i in $scope.modClassItem.userList) {
						if($scope.modClassItem.classes.userId == $scope.modClassItem.userList[i].userId) {
							$scope.modClassItem.select.userId = $scope.modClassItem.userList[i];
							break;
						}
					}
				}
			},  function(result) {
				if(result.status == 1) {
					alert(result.msg);
				}
			},  function() {
				$scope.$apply();
			});
    };
    // 修改班级
    $scope.editClasses = function() {
    	var data = {};
    	commonSrv.editClasses(data, function() {
    		if(data.status == 0) {
    			$("#editClassModel").modal('hide');
    		}
    	}, function(result) {
    		if(result.status == 1) {
    			alert(result.msg);
    		}
    	}, function() {
    		$scope.$apply();
    	})
    };
    // 添加班级其他老师表单
    $scope.addOtherUserForm = function() {
    	var data = {classesId: $scope.modClassItem.classes.classesId};
    	commonSrv.addOtherUserForm(data, function(result) {
    		if(result.status == 0) {
    			$scope.otherTea = result.data;
    			$('#otherTeaModel').modal({backdrop: 'static', show: true});
    		}
    	}, function(result) {
    		if(result.status == 1) {
    			alert(result.msg);
    		}
    	}, function() {
    		$scope.$apply();
    	})
    };
    $scope.addOtherUser = function() {

    }
    // 删除
    /**
     * 打开删除班级弹层
     * @param  {[type]} item [description]
     */
    $scope.openDel = function(item) {
    	$scope.delClassItem = item;
    	$('#delClassModel').modal('show');
    };
    /**
     * 删除班级
     */
    $scope.delClasses = function() {
    	var data = {
    		classesId: $scope.delClassItem.classesId
    	};
    	commonSrv.delClasses(data, function(result) {
    		if(result.status == 0) {
    			$scope.msg = "删除成功";
    			$scope.visible = true;
    			$scope.getClassesList($scope.curPage);
    		}
    	}, function(result) {
    		if(result.status == 1) {
    			alert(result.msg);
    		}
    	}, function() {
    		$("#delClassModel").modal('hide');
    		$scope.delClassItem = {};
    		$scope.$apply();
    	});
    };


    // 检测是否为空
    // 名称
    $scope.watchName = function(type) {
    	var nullWarn = "名称不能为空";
		if(type == 'new') {
			if(Tools.reg.isNull($scope.newClassItem.name)) {
				$scope.newClassItem.warn.name = nullWarn;
			} else {
				$scope.newClassItem.warn.name = "";
			}
		} else if(type == 'edit') {
			if(Tools.reg.isNull($scope.modClassItem.name)) {
				$scope.modClassItem.warn.name = nullWarn;
			} else {
				$scope.modClassItem.warn.name = "";
			}
		}
    }
    // 班级类型
    $scope.watchClassTypeId = function(type) {
    	var nullWarn = "请选择班级类型";
		if(type == 'new') {
			if($scope.newClassItem.select.classTypeId == null || !$scope.newClassItem.select.classTypeId.id) {
				$scope.newClassItem.warn.classTypeId = nullWarn;
			} else {
				$scope.newClassItem.warn.classTypeId = "";
			}
		} else if(type == 'edit') {
			if($scope.modClassItem.select.classTypeId == null || !$scope.modClassItem.select.classTypeId.id) {
				$scope.modClassItem.warn.classTypeId = nullWarn;
			} else {
				$scope.modClassItem.warn.classTypeId = "";
			}
		}
    }
    // 最大学生数
    $scope.watchMaxQuotas = function(type) {
    	var nullWarn = "请输入最大学生数(0~999)";
		if(type == 'new') {
			if(Tools.reg.isNull($scope.newClassItem.maxQuotas) && $scope.newClassItem.maxQuotas != 0) {
				$scope.newClassItem.warn.maxQuotas = nullWarn;
			} else {
				$scope.newClassItem.warn.maxQuotas = "";
			}
		} else if(type == 'edit') {
			if(Tools.reg.isNull($scope.modClassItem.maxQuotas) && $scope.modClassItem.maxQuotas != 0) {
				$scope.modClassItem.warn.maxQuotas = nullWarn;
			} else {
				$scope.modClassItem.warn.maxQuotas = "";
			}
		}
    }
    $scope.isString = function(input) {
    	return Tools.isString(input);
    }
    $scope.hide = function(name) {
    	Tools.hideModal(name);
    }
	// 初始化
	function init() {
		$scope.getClassTypeList();
		$scope.setYearList();
		$(document).ready(function() {
			// console.log($rootScope.secondType);
		});
	}
	init();
}]);